﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Road_temperature_monitoring
{  
    public partial class Form1 : Form
    {
        short distance = 0;
        private StringBuilder sb = new StringBuilder();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            int i;
            for (i = 300; i <= 38400; i = i * 2)
            {
                comboBox2.Items.Add(i.ToString());  //添加波特率列表
            }
            for (i = 300; i <= 38400; i = i * 2)
            {
                comboBox4.Items.Add(i.ToString());  //添加波特率列表
            }
            //获取电脑当前可用串口并添加到选项列表中
            comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
            comboBox3.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
            //批量添加波特率列表
            string[] baud = { "43000", "56000", "57600", "115200", "128000", "230400", "256000", "460800" };
            comboBox2.Items.AddRange(baud);
            comboBox2.Text = "9600";
            //批量添加波特率列表
            comboBox4.Items.AddRange(baud);
            comboBox4.Text = "115200";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (serialPort1.IsOpen)
                {
                    serialPort1.Close();    //关闭串口
                    button1.Text = "连接";
                    button1.BackColor = Color.Empty;
                    comboBox1.Enabled = true;
                    comboBox2.Enabled = true;
                }
                else
                {
                    //串口已经处于关闭状态，则设置好串口属性后打开
                    comboBox1.Enabled = false;
                    comboBox2.Enabled = false;
                    serialPort1.PortName = comboBox1.Text;
                    serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
                    //serialPort1.DataBits = Convert.ToInt16(comboBox3.Text);
                    serialPort1.Parity = System.IO.Ports.Parity.None;//
                    serialPort1.StopBits = System.IO.Ports.StopBits.One;
                    serialPort1.Open();     //打开串口
                    button1.Text = "连接成功";
                    button1.BackColor = Color.ForestGreen;
                    timer1.Interval = 1000;     //定时器赋初值
                    timer1.Start();     //启动定时器
                }
            }
            catch (Exception ex)
            {
                //捕获可能发生的异常并进行处理

                //捕获到异常，创建一个新的对象，之前的不可以再用
                serialPort1 = new System.IO.Ports.SerialPort();
                //刷新COM口选项
                comboBox1.Items.Clear();
                comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
                //响铃并显示异常给用户
                System.Media.SystemSounds.Beep.Play();
                button1.Text = "连接";
                button1.BackColor = Color.ForestGreen;
                button1.BackColor = Color.Empty;
                MessageBox.Show(ex.Message);
                comboBox1.Enabled = true;
                comboBox2.Enabled = true;
            }
        }

        private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {

            short temp = 0, hum = 0;
            //因为要访问UI资源，所以需要使用invoke方式同步ui
            int num = serialPort1.BytesToRead;      //获取接收缓冲区中的字节数
            byte[] received_buf = new byte[9];    //声明一个大小为num的字节数据用于存放读出的byte型数据
            serialPort1.Read(received_buf, 0, 9);   //读取接收缓冲区中num个字节到byte数组中
            sb.Clear();     //防止出错,首先清空字符串构造器
            this.Invoke((EventHandler)(delegate
            {
                temp = (short)(temp ^ received_buf[3]);
                temp = (short)(temp << 8);
                temp = (short)(temp ^ received_buf[4]);
                if (temp != 0)
                    TempDis.Text = temp.ToString().Insert(temp.ToString().Length - 2, ".") + "℃";
                if (distance < 200)
                {
                    stateDis.Text = "无效";
                    stateDis.BackColor = Color.Red;
                }
                else
                {
                    stateDis.Text = "有效";
                    stateDis.BackColor = Color.Green;
                }
            }
                   )
                );
        }

        private void SerialPort2_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                short temp = 0, hum = 0;
                //因为要访问UI资源，所以需要使用invoke方式同步ui
                int num = serialPort2.BytesToRead;      //获取接收缓冲区中的字节数
                byte[] received_buf = new byte[200];    //声明一个大小为num的字节数据用于存放读出的byte型数据


                //receive_count += num;                   //接收字节计数变量增加nun
                serialPort2.Read(received_buf, 0, num);   //读取接收缓冲区中num个字节到byte数组中

                sb.Clear();     //防止出错,首先清空字符串构造器
                this.Invoke((EventHandler)(delegate
                {
                    temp = (short)(temp ^ received_buf[3]);
                    temp = (short)(temp << 8);
                    temp = (short)(temp ^ received_buf[2]);
                    distance = temp;
                    if (temp != 0)
                        disDis.Text = temp.ToString() + "cm";

                }
                   )
                );

            }
            catch (Exception ex)
            {
                //响铃并显示异常给用户
                System.Media.SystemSounds.Beep.Play();
                MessageBox.Show(ex.Message);

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (serialPort2.IsOpen)
                {
                    serialPort2.Close();    //关闭串口
                    button3.Text = "连接";
                    button3.BackColor = Color.Empty;
                    comboBox3.Enabled = true;
                    comboBox4.Enabled = true;
                }
                else
                {
                    //串口已经处于关闭状态，则设置好串口属性后打开
                    comboBox3.Enabled = false;
                    comboBox4.Enabled = false;
                    serialPort2.PortName = comboBox3.Text;
                    serialPort2.BaudRate = Convert.ToInt32(comboBox4.Text);
                    //serialPort1.DataBits = Convert.ToInt16(comboBox3.Text);
                    serialPort2.Parity = System.IO.Ports.Parity.None;//
                    serialPort2.StopBits = System.IO.Ports.StopBits.One;
                    serialPort2.Open();     //打开串口
                    button3.Text = "连接成功";
                    button3.BackColor = Color.ForestGreen;
                }
            }
            catch (Exception ex)
            {
                //捕获可能发生的异常并进行处理

                //捕获到异常，创建一个新的对象，之前的不可以再用
                serialPort2 = new System.IO.Ports.SerialPort();
                //刷新COM口选项
                comboBox3.Items.Clear();
                comboBox3.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
                //响铃并显示异常给用户
                System.Media.SystemSounds.Beep.Play();
                button3.Text = "连接";
                button3.BackColor = Color.ForestGreen;
                button3.BackColor = Color.Empty;
                MessageBox.Show(ex.Message);
                comboBox3.Enabled = true;
                comboBox4.Enabled = true;
            }
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            byte[] temp = new byte[1];
            if (serialPort1.IsOpen)
            {
                try
                {
                    // string buf = "01 03 00 00 00 02 c4 0b";
                    string buf = "01 03 00 00 00 02 c4 0b";
                    string pattern = @"\s";
                    string replacement = "";
                    Regex rgx = new Regex(pattern);
                    string send_data = rgx.Replace(buf, replacement);

                    //不发送新行
                    //num = (send_data.Length - send_data.Length % 2) / 2;
                    for (int i = 0; i < 8; i++)
                    {
                        temp[0] = Convert.ToByte(send_data.Substring(i * 2, 2), 16);
                        serialPort1.Write(temp, 0, 1);  //循环发送
                    }
                }
                catch (Exception ex)
                {

                }
            }

        }
    }
}
